package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Usuario;
import dao.UsuarioDao;

/**
 * Servlet implementation class login
 */
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String senha = request.getParameter("senha");

		System.out.println(login);
		System.out.println(senha);

		Usuario usuario = new Usuario();
		usuario = UsuarioDao.buscarUsuarioPorEmail(login);
		if(usuario != null){
			if(login.equals(usuario.getNomeDeUsuario())){
				if(senha.equals(usuario.getSenha())){
					if(login.equals("admin")){
						System.out.println("Conectado como administrador!");
						HttpSession session = request.getSession();
						session.setAttribute("LOGIN", usuario.getNomeDeUsuario());

						RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
						rd.include(request, response);
					}
					else{
						System.out.println("Conectado!");
						HttpSession session = request.getSession();
						session.setAttribute("LOGIN", usuario.getNomeDeUsuario());

						RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
						rd.include(request, response);
					}
				}
			}
		}

		else{

			RequestDispatcher rd = request.getRequestDispatcher("erroLogin.jsp");
			rd.include(request, response);
		}		}
}
